﻿using DNFImagePacks2Manager.Helpers;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;

namespace DNFImagePacks2Manager.Models
{
    public class NPKCustomJson(string filename, string? path = null) : NPKCustomBase(filename, path)
    {
        public override List<NPKItemBase> GetNPKItemList()
        {
            List<NPKItemBase> npkList = [];
            if (File.Exists(CsmFile))
            {
                try
                {
                    string ImagePrefix = NPKItemImage.NamePrefix;
                    string SoundPrefix = NPKItemSound.NamePrefix;
                    string ImageBasePath = LocalStorageHelper.GetImagePath();
                    string SoundBasePath = LocalStorageHelper.GetSoundPath();
                    var items = ReadCsmFile();
                    foreach (var item in items)
                    {
                        string type = item.type;
                        NPKItemBase? npk = null;

                        if (string.Equals(ImagePrefix, type))
                        {
                            npk = NPKItemImage.GetImageNPKItem(item.name, ImageBasePath);
                        }
                        else if (string.Equals(SoundPrefix, type))
                        {
                            npk = NPKItemSound.GetSoundNPKItem(item.name, SoundBasePath);
                        }

                        if(npk != null)
                        {
                            npkList.Add(npk);
                        }
                    }
                }
                catch (Exception) { }
            }
            return npkList;
        }

        public override List<string> GetNPKNameList()
        {
            List<string> npkList = [];
            if (File.Exists(CsmFile))
            {
                try
                {
                    var items = ReadCsmFile();
                    foreach (var item in items)
                    {
                        npkList.Add($"{item.type}: {item.name}");
                    }
                }
                catch (Exception) { }
            }
            return npkList;
        }

        public List<NPKCustomJsonNode> ReadCsmFile()
        {
            List<NPKCustomJsonNode> list = [];
            string file = CsmFile;
            if (File.Exists(file))
            {
                try
                {
                    string json = File.ReadAllText(file);
                    var items = JsonConvert.DeserializeObject<List<NPKCustomJsonNode>>(json);
                    if (items != null)
                    {
                        return items;
                    }
                }
                catch (Exception)
                {
                }
            }
            return list;
        }
    }
}
